package com.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bean.ResponseBean;
import com.dao.GoodsTypeDAO;
import com.pojo.Goods;
import com.pojo.GoodsType;
import com.service.GoodsService;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author:TTW
 * @Discription:处理商品相关请求
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsTypeDAO goodsTypeDAO;
    @Value("${upload.dir}")
    private String upload;
    @Value("${upload.tmp.dir}")
    private String tmp;

    /**
     * 新增商品(超级管理员)
     *
     * @param goods   商品
     * @return
     */
    @RequestMapping("/goodsAddAdmin")
    public ResponseBean addGoodsAdmin(Goods goods) {
        System.out.println(goods);
        String ss = judgeGoods(goods);
        if (ss == null) {
            //插入商品
            goods.setCreatetime(new Date());
            Goods newGoods = goodsService.addGoods(goods);
            //插入商品图片
//            goodsService.addGoodsImages(newGoods, image0, image1, image2, image3, image4);

            return new ResponseBean(200, "新增成功", goods);
        } else {
            return new ResponseBean(500, "参数异常", ss);
        }
    }

    /**
     * 添加商品的图片
     * @param id 商品id
     * @param image0 中文图片
     * @param image1 中文图片
     * @param image2 中文图片
     * @param image3 中文图片
     * @param image4 中文图片
     * @param image5 英文图片
     * @param image6 英文图片
     * @param image7 英文图片
     * @param image8 英文图片
     * @param image9 英文图片
     * @param image10 泰文图片
     * @param image11 泰文图片
     * @param image12 泰文图片
     * @param image13 泰文图片
     * @param image14 泰文图片
     * @param image15 柬埔寨图片
     * @param image16 柬埔寨图片
     * @param image17 柬埔寨图片
     * @param image18 柬埔寨图片
     * @param image19 柬埔寨图片
     * @return
     */
    @RequestMapping("/addGoodsPicture")
    public ResponseBean addGoodsPicture(String id,String image0,String image1,String image2,String image3,String image4,String image5,String image6,String image7,String image8,String image9,String image10,String image11,String image12,String image13,String image14,String image15,String image16,String image17,String image18,String image19){
        try{
            goodsService.addGoodsImages(id,image0,image1,image2,image3,image4,1);//添加中文轮播图
            goodsService.addGoodsImages(id,image5,image6,image7,image8,image9,2);//添加英文轮播图
            goodsService.addGoodsImages(id,image10,image11,image12,image13,image14,3);//添加泰文轮播图
            goodsService.addGoodsImages(id,image15,image16,image17,image18,image19,4);//添加柬埔寨轮播图
            return ResponseBean.ok("成功");
        }catch (Exception e){
            System.out.println(e);
            e.printStackTrace();
            return ResponseBean.error("图片上传失败");
        }
    }

    /**
     * 添加商品的图片
     * @param id 商品id
     * @param image0 中文图片
     * @param image1 中文图片
     * @param image2 中文图片
     * @param image3 中文图片
     * @param image4 中文图片
     * @param image5 英文图片
     * @param image6 英文图片
     * @param image7 英文图片
     * @param image8 英文图片
     * @param image9 英文图片
     * @param image10 泰文图片
     * @param image11 泰文图片
     * @param image12 泰文图片
     * @param image13 泰文图片
     * @param image14 泰文图片
     * @param image15 柬埔寨图片
     * @param image16 柬埔寨图片
     * @param image17 柬埔寨图片
     * @param image18 柬埔寨图片
     * @param image19 柬埔寨图片
     * @return
     */
    @RequestMapping("/updateGoodsPicture")
    public ResponseBean updateGoodsPicture(String id,String image0,String image1,String image2,String image3,String image4,String image5,String image6,String image7,String image8,String image9,String image10,String image11,String image12,String image13,String image14,String image15,String image16,String image17,String image18,String image19){
        try{
            goodsService.updateGoodsImages(id,image0,image1,image2,image3,image4,1);//添加中文轮播图
            goodsService.updateGoodsImages(id,image5,image6,image7,image8,image9,2);//添加英文轮播图
            goodsService.updateGoodsImages(id,image10,image11,image12,image13,image14,3);//添加泰文轮播图
            goodsService.updateGoodsImages(id,image15,image16,image17,image18,image19,4);//添加柬埔寨轮播图
            return ResponseBean.ok("成功");
        }catch (Exception e){
            System.out.println(e);
            e.printStackTrace();
            return ResponseBean.error("图片上传失败");
        }
    }

    /**
     * 用于判断新增或修改的商品是否符合规范
     *
     * @return
     */
    private String judgeGoods(Goods goods) {
        if (StringUtil.isNull(goods.getGName())) {
            return "中文名称不能为空";
        }
        if (StringUtil.isNull(goods.getGName_tai())) {
            return "泰语名称不能为空";
        }
        if (StringUtil.isNull(goods.getGPinpai())) {
            return "中文品牌不能为空";
        }
        if (StringUtil.isNull(goods.getGPinpai_tai())) {
            return "泰语品牌不能为空";
        }
        if (StringUtil.isNull(goods.getGDanwei())) {
            return "中文计量单位不能为空";
        }
        if (StringUtil.isNull(goods.getGDanwei_tai())) {
            return "泰语计量单位不能为空";
        }
        if (StringUtil.isNull(goods.getGChandi())) {
            return "中文生产地不能为空";
        }
        if (StringUtil.isNull(goods.getGChandi_tai())) {
            return "泰语生产地不能为空";
        }
        if (goods.getGPrice_tai()==null){
            return "泰铢价格不能为空";
        }
        if (goods.getGPrice()==null){
            return "人民币价格不能为空";
        }
        if (goods.getGKucun()==null){
            return "库存不能为空";
        }
        if (StringUtil.isNull(goods.getGJianjie())){
            return "中文简介不能为空";
        }
        if (StringUtil.isNull(goods.getGJianjie_tai())){
            return "泰文简介不能为空";
        }
        if (goods.getOriginalPrice()==null){
            return "人民币原价不能为空";
        }
        if (goods.getOriginalPrice_tai()==null){
            return "泰语原价不能为空";
        }
        return null;
    }

    /**
     * 搜索商品  商品列表
     *
     * @param request
     * @param name    商品名称
     * @param status  状态（0下架  1上架）
     * @param tuijian 是否推荐（0否   1是）
     * @param page    页数
     * @param limit   条数
     * @return
     */
    @RequestMapping("/searchGoods")
    public ResponseBean searchGoods(HttpServletRequest request, String name, @RequestParam(defaultValue = "-1") Integer status, @RequestParam(defaultValue = "-1") Integer tuijian, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit) {
        IPage iPage = goodsService.searchGoods(name, status, tuijian, page, limit);
        return new ResponseBean(0, iPage.getTotal(), "查询成功", iPage.getRecords());
    }

    /**
     * 商品上架
     *
     * @param gid 商品ID
     * @return
     */
    @RequestMapping("/goodsUp")
    public synchronized ResponseBean goodsUp(String gid) {
        Goods goods = goodsService.getById(gid);
        if (goods == null) {
            return new ResponseBean(404, "商品不存在", null);
        }
        goods.setGStatus(1);
        goodsService.updateById(goods);
        return new ResponseBean(200, "上架成功", null);
    }

    /**
     * 商品推荐
     *
     * @param gid 商品ID
     * @return
     */
    @RequestMapping("/tuiUp")
    public synchronized ResponseBean tuiUp(String gid) {
        Goods goods = goodsService.getById(gid);
        if (goods == null) {
            return new ResponseBean(404, "商品不存在", null);
        }
        goods.setTuijian(1);
        goodsService.updateById(goods);
        return new ResponseBean(200, "推荐成功", null);
    }

    /**
     * 取消推荐
     *
     * @param gid 商品ID
     * @return
     */
    @RequestMapping("/tuiDown")
    public synchronized ResponseBean tuiDown(String gid) {
        Goods goods = goodsService.getById(gid);
        if (goods == null) {
            return new ResponseBean(404, "商品不存在", null);
        }
        goods.setTuijian(0);
        goodsService.updateById(goods);
        return new ResponseBean(200, "取消成功", null);
    }

    /**
     * 查询推荐商品
     *
     * @param yuyan
     * @return
     */
    @RequestMapping("/allTuijian")
    public synchronized ResponseBean allTuijian(String yuyan, String type) {
        List list = new ArrayList();
        list = goodsService.getAllTuijian(yuyan, type);
        return new ResponseBean(200, "查询成功", list);
    }

    /**
     * 商品下架
     *
     * @param gid 商品ID
     * @return
     */
    @RequestMapping("/goodsDown")
    public ResponseBean goodsDown(String gid) {
        Goods goods = goodsService.getById(gid);
        if (goods == null) {
            return new ResponseBean(404, "商品不存在", null);
        }
        goods.setGStatus(0);
        goodsService.updateById(goods);
        return new ResponseBean(200, "下架成功", null);
    }

    /**
     * 根据商品ID查找商品信息
     *
     * @param goodsID 商品ID
     * @return
     */
    @RequestMapping("/getGoodsById")
    public ResponseBean getGoodsById(String goodsID) {
        Goods goods = goodsService.getById(goodsID);
        if (goods == null) {
            return new ResponseBean(404, "商品不存在", null);
        }
        GoodsType goodsType = goodsTypeDAO.selectById(goods.getGTypeId());
        goods.setGoodsType(goodsType);
        return new ResponseBean(200, "获取成功", goods);
    }

    /**
     * 修改商品
     *
     * @param goods  商品对象
     * @return
     */
    @RequestMapping("/goodsUpdate")
    public ResponseBean goodsUpdate(Goods goods) {
        String ss = judgeGoods(goods);
//        if (goods.getGrabPrice()==null){
//            goods.setGrabPrice(new BigDecimal(0));
//        }
//        if (goods.getGrabPrice_en()==null){
//            goods.setGrabPrice_en(new BigDecimal(0));
//        }
//        if (goods.getGrabPrice()==null){
//            goods.setGrabPrice_tai(new BigDecimal(0));
//        }
//        System.out.println(goods.getGrabPrice());
        if (ss == null) {
            String img =goods.getGPicture();
            if (img.startsWith("images")) {
                goods.setGPicture(img);
            } else {
                goods.setGPicture("images/goods/" + img);
                FileUtil.copy(tmp + img, upload + "images/goods/" + img, true);
            }

            String guige = goods.getGuige();
            if (StringUtil.isNotNull(guige)) {
                JSONObject jsonObject = JSONObject.parseObject(guige);
                JSONArray array = jsonObject.getJSONArray("values");
                if (array != null) {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject value = array.getJSONObject(i);
                        if (!value.getString("img").startsWith("images")){
                            String img2 = value.getString("img");
                            FileUtil.copy(tmp + img2, upload + "images/goods/", true);
                            value.put("img", "images/goods/" + img2);
                        }
                    }
                }
                goods.setGuige(jsonObject.toJSONString());
            }

            goodsService.updateById(goods);
//            goodsService.updateGoodsImages(goods, image0, image1, image2, image3, image4, image5);

            return new ResponseBean(200, "修改成功", goods);
        } else {
            return new ResponseBean(500, "参数异常", ss);
        }
    }


    /**
     * 查询所有上架商品
     *
     * @return
     */
    @RequestMapping("/searchAllShangjia")
    public ResponseBean searchAllShangjia() {
        return new ResponseBean(200, "查询成功", goodsService.list(new QueryWrapper<Goods>().eq("gStatus", 1)));
    }

    /**
     * 根据商品名称分页查询
     *
     * @param page      页数
     * @param limit     条数
     * @param goodsName 搜索内容
     * @param yuyan     语言
     * @return
     */
    @CrossOrigin
    @RequestMapping("/searchGoodsPage")
    public ResponseBean searchGoodsPage(int page, int limit, String goodsName, String yuyan) {
        IPage iPage = goodsService.getPageName(page, limit, goodsName, yuyan);
        return new ResponseBean(200, iPage.getTotal(), iPage);
    }

    /**
     * 根据商品id查询商品基本信息
     *
     * @param id    商品id
     * @param yuyan 语言
     * @return
     */
    @CrossOrigin
    @RequestMapping("/getGoodsDetailById")
    public ResponseBean getGoodsDetailById(String id, String yuyan, HttpServletRequest request) {
        Goods goods = goodsService.getGoodsById(id, request.getServerName() + ":" + request.getServerPort(), yuyan);

        if (goods != null) {
            return new ResponseBean(200, "查询成功", goods);
        } else {
            return new ResponseBean(500, "查询失败", goods);
        }
    }

    /**
     * 根据商品类别id分页查询商品
     *
     * @param typeId 商品类型id
     * @param page   页数
     * @param limit  条数
     * @param yuyan  判断语言取相应的语言字段
     * @return
     */
    @CrossOrigin
    @RequestMapping("/getGoodsPageByType")
    public ResponseBean getGoodsPageByType(String typeId, int page, int limit, String yuyan) {
        Page p = new Page(page, limit);
        QueryWrapper<Goods> qw = new QueryWrapper<>();
        if (StringUtil.isNotNull(typeId)) {
            qw.eq("gTypeId", typeId);
        }
        qw.eq("gStatus", 1);
        qw.orderByDesc("weights");
        IPage iPage1 = goodsService.getPage(p, qw, yuyan);
        return new ResponseBean(200, iPage1.getTotal(), iPage1);
    }

    /**
     * 下载excel模板
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/exportExcel")
    public ResponseEntity<InputStreamResource> exportExcelForPPUser() throws IOException {
        String cnFileName = new String("商品批量导入模板".getBytes(), "utf-8");
        String name = cnFileName + new Date().getTime() + ".xls";
        String fileName = upload + "/excel/" + name;
        if (!new File(upload + "/excel/").exists()) {
            new File(upload + "/excel/").mkdirs();
        }
        try {
            goodsService.exportExcel(fileName,"商品批量导入模板");
        } catch (Exception e) {
            e.printStackTrace();
        }

        FileSystemResource file = new FileSystemResource(fileName);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }

    /**
     * 批量导入商品
     *
     * @param file excel文件
     * @return
     */
    @PostMapping(value = "/importGoodsExcel")
    public ResponseBean importGoodsExcel(@RequestParam MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        Map<String, Object> map = new HashMap<>();
//        List<Goods> businessList = new ArrayList<>();
//        Map<String, String> resultMap = ExcelUtil.importExcelByBusiness(fileName, file,businessList);
        List<Goods> goodsList = new ArrayList<>();
        Map<String, String> resultMap = goodsService.importExcelByGoods(file, goodsList);
        if (resultMap.containsKey("error")) {
            return new ResponseBean(500, "失败", resultMap.get("error"));
        }
        if (resultMap.containsKey("sucess")) {
            if (goodsService.saveBatch(goodsList)) {
                return new ResponseBean(200, "导入成功", goodsList);
            }
        }
        return new ResponseBean(500, "失败", "导入失败");
    }

    /**
     * 根据id删除商品
     * @param id 商品id
     * @return
     */
    @RequestMapping("/deleteById")
    public ResponseBean deleteById(String id){
        try{
            Goods goods =goodsService.getById(id);
            if (goods!=null){
                if (goodsService.removeById(goods.getId())){
                    return new ResponseBean(200,"删除成功",null);
                }else{
                    return new ResponseBean(500,"删除失败",goods);
                }
            }else{
                return new ResponseBean(500,"未找到该商品",id);
            }
        } catch (Exception e){
            return new ResponseBean(500,"系统异常",null);
        }
    }

//    /**
//     * 解析word文档
//     * @param fileName word文档的文件名字
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping("/analysisWord")
//    public ResponseBean analysisWord(@RequestParam("fileName") String fileName) throws Exception {
//        String filePath=tmp+fileName;
//        String readfile= WordToHtmlBackStringUtil.convert(filePath);
//        return new ResponseBean(200,0,"解析成功",readfile);
//    }
}
